const express = require('express');
const constant = require('../data/constant');
const mysql = require('mysql');
const config = require('config');

function project_auth(req,res,next){
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME,
        'multipleStatements': true // 支持执行多条 sql 语句
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            // 构造sql语句
            // 是项目成员 或 项目开放
            let  sql = "SELECT * FROM project_member WHERE pid = ? and uid = ?;"+
            "SELECT * FROM project WHERE pid = ? and isFinished = ?;";
            let  sqlParams = [
                parseInt(req.query.project_id),
                req.user.uid,
                parseInt(req.query.project_id),
                true
            ];
            // console.log(sql,sqlParams);
            connection.query(sql,sqlParams,async (err,data) => {
                if(err){
                    console.log(err);
                    res.statusCode = 500;
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                }else{
                    let res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                    res_data = JSON.parse(res_data);//把results字符串转为json对象
                    if(res_data[0].length >= 1 || res_data[1].length >= 1){// 是项目成员 或 项目开放
                       next();
                    }else{
                        res.send({
                            res:{
                                ok:0,
                                msg:"您不是该项目成员，无权访问！"
                            }
                        })
                    }
                }
            });
            connection.release();
        }
    });
}
module.exports = project_auth;